import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:path_provider/path_provider.dart';
import 'package:realmega_ota/realmega/history_info.dart';

import '../util/log_util.dart';

class HistoryManager{

  HistoryManager._();

  static final HistoryManager _instance = HistoryManager._();
  static HistoryManager get instance => _instance;

  final StreamController<List<HistoryInfo>> _controller = StreamController.broadcast();

  Stream<List<HistoryInfo>> get runningHistory => _controller.stream.asBroadcastStream();

  StreamSink<List<HistoryInfo>> get _sink => _controller.sink;

  List<HistoryInfo> _historyList = [];


  // void addHistory(HistoryInfo info){
  //   // Log.d("add log:$log");
  //   _historyList.add(info);
  //   _sink.add(_historyList);
  // }

  void close(){
    _controller.close();
  }

  void loadHistoryList() {

    // if(true){
    //   List<HistoryInfo> temp = [];
    //   HistoryInfo his = HistoryInfo(1, "ble_ota", 'bb:ee:cc:dd:ff:12', '成功', '2023-05-26 21:19:33', '升级成功');
    //   temp.add(his);
    //   his = HistoryInfo(1, "ble_ota", 'bb:ee:cc:dd:ff:12', '成功', '2023-05-26 21:19:33', '升级成功');
    //   temp.add(his);
    //   his = HistoryInfo(1, "ble_ota", 'bb:ee:cc:dd:ff:12', '失败', '2023-05-26 21:19:33', 'mac地址不对');
    //   temp.add(his);
    //   his = HistoryInfo(1, "ble_ota", 'bb:ee:cc:dd:ff:12', '成功', '2023-05-26 21:19:33', '升级成功');
    //   temp.add(his);
    //   his = HistoryInfo(1, "ble_ota", 'bb:ee:cc:dd:ff:12', '失败', '2023-05-26 21:19:33', 'mac地址不对');
    //   temp.add(his);
    //   his = HistoryInfo(1, "ble_ota", 'bb:ee:cc:dd:ff:12', '成功', '2023-05-26 21:19:33', '升级成功');
    //   temp.add(his);
    //   his = HistoryInfo(1, "ble_ota", 'bb:ee:cc:dd:ff:12', '失败', '2023-05-26 21:19:33', 'mac地址不对');
    //   temp.add(his);
    //   his = HistoryInfo(1, "ble_ota", 'bb:ee:cc:dd:ff:12', '成功', '2023-05-26 21:19:33', '升级成功');
    //   temp.add(his);
    //   his = HistoryInfo(1, "ble_ota", 'bb:ee:cc:dd:ff:12', '失败', '2023-05-26 21:19:33', 'mac地址不对');
    //   temp.add(his);
    //   return temp;
    // }

    Directory? documentsDir;
    if(Platform.isAndroid){
      getExternalStorageDirectory().then((value) {
        _readHistoryInternal(value);
      });
    }else if(Platform.isIOS){
      getApplicationDocumentsDirectory().then((value) {
        _readHistoryInternal(value);
      });
    }else{

    }

  }

  void _readHistoryInternal(documentsDir){
    String? documentsPath = documentsDir?.path;

    File file = File('$documentsPath/history_cache.log');
    if(!file.existsSync()) {
      return;
    }

    file.readAsString().then((value) {
      List listJson = json.decode(value);
      _historyList = listJson.map((m) => HistoryInfo.fromJson(m)).toList();
      _sink.add(_historyList);
    });
  }

  void saveHistory(HistoryInfo info){
    _historyList.add(info);
    _sink.add(_historyList);

    if(Platform.isAndroid){
      getExternalStorageDirectory().then((value) {
        _saveHistoryInternal(value!, json.encode(_historyList));
      });
    }else if(Platform.isIOS){
      getApplicationDocumentsDirectory().then((value) {
        _saveHistoryInternal(value, json.encode(_historyList));
      });
    }else{
      throw UnsupportedError('not support platform ${Platform.localeName}');
    }
  }

  void _saveHistoryInternal(Directory value, String notes){
    File file = File('${value.path}/history_cache.log');
    if(!file.existsSync()) {
      file.createSync(recursive: true);
    }
    file.writeAsString(notes, flush: true);
    if(file.existsSync()) {
      Log.d('历史记录：$notes保存成功');
    }
  }

  void clearHistory(){
    _historyList.clear();
    _sink.add(_historyList);

    if(Platform.isAndroid){
      getExternalStorageDirectory().then((value) {
        _saveHistoryInternal(value!, '');
      });
    }else if(Platform.isIOS){
      getApplicationDocumentsDirectory().then((value) {
        _saveHistoryInternal(value, '');
      });
    }else{
      throw UnsupportedError('not support platform ${Platform.localeName}');
    }
  }
}